package com.helen.ui.address;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.AddressListAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.AddressListEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.cache.converter.SerializableDiskConverter;
import com.zhouyou.http.cache.model.CacheMode;
import com.zhouyou.http.cache.model.CacheResult;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/4/26.
 * 地址列表
 */

public class AddressListActivity extends BaseActivity {
    private static final int ADD_ADDRESS = 0x33;
    private static final int UPDATE_ADDRESS = 0x44;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.tv_add_address)
    SuperTextView tvAddAddress;
    private AddressListAdapter addressListAdapter;
    private List<AddressListEntity> list = new ArrayList<>();
    private View errorView;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_address_list;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.address_manager);
        errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) rvList.getParent(), false);
        addressListAdapter = new AddressListAdapter(R.layout.item_address_list, list,0);
        addressListAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        swipeRefresh.setRefreshing(true);
        swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.appThemeColor));
        rvList.setLayoutManager(new LinearLayoutManager(AddressListActivity.this));
        rvList.setAdapter(addressListAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });


        addressListAdapter.setOnItemDefaultListener(new AddressListAdapter.OnSetItemDefaultListener() {
            @Override
            public void setOnDefaultListener(AddressListEntity addressListEntity, int position) {
                if (addressListAdapter.getData().size() > 0) {
                    for (int i = 0; i < addressListAdapter.getData().size(); i++) {
                        addressListAdapter.getItem(i).setIsDefault("0");
                    }
                    MyLog.e("yang", "position==" + position);
                    addressListAdapter.getItem(position).setIsDefault("1");
                    addressListAdapter.notifyDataSetChanged();
                    setDefaultAddressApi(addressListEntity.getId());
                }

            }
        });


        addressListAdapter.setOnItemEditListener(new AddressListAdapter.OnSetItemEditListener() {
            @Override
            public void setOnEditListener(AddressListEntity addressListEntity, int position) {
                Intent ti = new Intent(AddressListActivity.this, AddNewAddressActivity.class);
                ti.putExtra("addressListEntity", addressListEntity);
                startActivityForResult(ti, UPDATE_ADDRESS);
            }
        });

        addressListAdapter.setOnItemDeleteListener(new AddressListAdapter.OnSetItemDeleteListener() {
            @Override
            public void setOnDeleteListener(AddressListEntity addressListEntity, int position) {
                MyLog.e("yang", "删除");
                deleteAddresssApi(addressListEntity.getId(), position);
            }
        });


        addressListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AddressListEntity addressListEntity = (AddressListEntity) adapter.getData().get(position);
                if (getIntent().getBooleanExtra("backModel", false)) {
                    Intent ti = new Intent();
                    ti.putExtra("addressListEntity", addressListEntity);
                    setResult(RESULT_OK, ti);
                    finish();
                }
            }
        });

        refresh();
    }

    private void refresh() {
        addressListApi();
    }

    @Override
    protected void updateViews() {

    }

    //    获取地址列表
    private void addressListApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(AddressListActivity.this).getId() + "");
        EasyHttp.post(Constants.API_JSONAPI_ADDRESSLIST)
                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
                .cacheKey(Constants.API_JSONAPI_ADDRESSLIST)
                .cacheDiskConverter(new SerializableDiskConverter())
                .params(params)
                .execute(new SimpleCallBack<CacheResult<String>>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                        swipeRefresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "地址管理失败==" + e.toString());
                        MToast.makeTextShort(AddressListActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(CacheResult<String> stringCacheResult) {
                        String data = PhoneUtils.checkResponseFlag2(AddressListActivity.this, stringCacheResult.data, TAG);
                        if (data != null && !data.equals("[]")) {
                            list = new Gson().fromJson(data, new TypeToken<List<AddressListEntity>>() {
                            }.getType());
                            addressListAdapter.setNewData(list);
                        } else {
                            addressListAdapter.getData().clear();
                            addressListAdapter.setEmptyView(errorView);
                        }
                    }
                });
    }


    //    删除地址
    private void deleteAddresssApi(String id, final int position) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(AddressListActivity.this).getId());
        params.put("id", id);
        EasyHttp.post(Constants.API_JSONAPI_DELETEADDRESS)
                .params(params)
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", "删除地址失败==" + e.toString());
                        MToast.makeTextLong(AddressListActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(AddressListActivity.this, result, TAG);
                        if (data != null) {
                            MToast.makeTextLong(AddressListActivity.this, "删除成功").show();
                            addressListAdapter.remove(position);
                            addressListAdapter.notifyDataSetChanged();
                        }

                    }
                });
    }


    //    设置默认地址
    private void setDefaultAddressApi(String iid) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(AddressListActivity.this).getId() + "");
        params.put("iid", iid );
        EasyHttp.post(Constants.API_JSONAPI_SETDEFAULT)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", "设置默认地址失败==" + e.toString());
                        MToast.makeTextLong(AddressListActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(AddressListActivity.this, result, TAG);
                        if (data != null) {
                            MToast.makeTextLong(AddressListActivity.this, "默认地址设置成功").show();
                        }
                    }
                });

    }

    @OnClick(R.id.tv_add_address)
    public void onViewClicked() {
        Intent ti = new Intent(AddressListActivity.this, AddNewAddressActivity.class);
        startActivityForResult(ti, ADD_ADDRESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ADD_ADDRESS:
                    refresh();
                    break;
                case UPDATE_ADDRESS:
                    refresh();
                    break;
            }
        }
    }
}
